import { Message } from 'element-ui'
// 根据身份证获得年龄
export function idAge(identityCard) {
  var len = (identityCard + '').length
  if (len === 0) {
    return Message({
      showClose: true,
      message: '身份证号码不能为空',
      duration: 3000,
      type: 'warning'
    })
  } else {
    if (len !== 15 && len !== 18) {
      // 身份证号码只能为15位或18位其它不合法
      return Message({
        showClose: true,
        message: '身份证号码应为15位或18位',
        duration: 3000,
        type: 'warning'
      })
    }
  }
  var strBirthday = ''
  if (len === 18) {
    // 处理18位的身份证号码从号码中得到生日和性别代码
    strBirthday =
      identityCard.substr(6, 4) +
      '/' +
      identityCard.substr(10, 2) +
      '/' +
      identityCard.substr(12, 2)
  }
  if (len === 15) {
    strBirthday =
      '19' +
      identityCard.substr(6, 2) +
      '/' +
      identityCard.substr(8, 2) +
      '/' +
      identityCard.substr(10, 2)
  }
  // 时间字符串里，必须是“/”
  var birthDate = new Date(strBirthday)
  var nowDateTime = new Date()
  var age = nowDateTime.getFullYear() - birthDate.getFullYear()
  // 再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  if (
    nowDateTime.getMonth() < birthDate.getMonth() ||
    (nowDateTime.getMonth() === birthDate.getMonth() &&
      nowDateTime.getDate() < birthDate.getDate())
  ) {
    age--
  }
  return age
}
// 将金额改写为大写
export function capitalizationAmount(data) {
  var fraction = ['角', '分']
  var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  var unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  var head = data < 0 ? '欠' : ''
  data = Math.abs(data)
  var s = ''
  for (var i = 0; i < fraction.length; i++) {
    s += (
      digit[Math.floor(data * 10 * Math.pow(10, i)) % 10] + fraction[i]
    ).replace(/零./, '')
  }
  s = s || '整'
  data = Math.floor(data)
  for (i = 0; i < unit[0].length && data > 0; i++) {
    var p = ''
    for (var j = 0; j < unit[1].length && data > 0; j++) {
      p = digit[data % 10] + unit[1][j] + p
      data = Math.floor(data / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  return (
    head +
    s
      .replace(/(零.)*零元/, '元')
      .replace(/(零.)+/g, '零')
      .replace(/^整$/, '零元整')
  )
}
